<?php


namespace App\Shuixing\Controllers;


use App\Lib\JwtAuth;
use App\Models\Posts\WxComment;
use App\Models\Posts\WxLike;
use App\Models\Posts\WxPost;
use App\Models\Posts\WxPostsImg;
use App\Models\Posts\WxPostsTag;
use App\Models\Posts\WxPostsVideo;
use App\Models\Posts\WxTag;
use App\Models\WxUser;

class TagController
{
    public function index($id = 0)
    {

        View()->composer('shuixing/home', function ($view) {
            $view->with(['menu' => 3]);
        });

//        全部标签板块
        $tag = WxTag::where('tags_state', 0)
            ->where('tags_number', '>', 1)
            ->orderBy('sort', 'asc')
            ->get();

        // 按标签获取帖子
        if ($id == 0) {
            $data = (new WxPost())->where('is_examine', 1)
                ->where('posts_state', 0)->orderBy('id', 'desc')->get();
            $data = self::postsParame($data);//文章详情
        } else {
            $postIdsArr = WxPostsTag::where('tags_id', $id)->pluck('posts_id');
            $data = (new WxPost())->where('is_examine', 1)
                ->where('posts_state', 0)->whereIn('id', $postIdsArr)
                ->orderBy('id', 'desc')->get();
            $data = self::postsParame($data);//文章详情
        }


        return view('shuixing/tag', ['data' => $data, 'tag' => $tag, 'type' => $id]);
    }

    public static function postsParame($data)
    {
        $data->map(function ($item, $key) use ($data) {
            if (WxPostsImg::where('posts_id', $item->id)->exists() || WxPostsVideo::where('posts_id', $item->id)->exists()) {
                $img_url = WxPostsImg::where('posts_id', $item->id)->value('img_url');
                if ($img_url) {
                    $item->img = $img_url;
                } else {
                    $item->img = WxPostsVideo::where('posts_id', $item->id)->value('video_thumb_url');
                }
                $tagsIds = WxPostsTag::where('posts_id', $item->id)->pluck('tags_id');
                $item->tags = WxTag::whereIn('id', $tagsIds)->get(['tags_name', 'id']);
                $item->like_count = WxLike::where('posts_id', $item->id)->count();
                $item->comment_count = WxComment::where(['posts_id' => $item->id, 'comment_state' => 1])->count();
                $item->format_time = format_datetime($item->created_at);
                $item->user = WxUser::where('id', $item->user_id)->first(['id', 'user_name', 'user_avatar', 'is_member', 'is_official', 'is_authentication']);
            } else {
                unset($data[$key]);
            }
        });
        $data = $data->toArray();
        $data = array_values($data);

        return $data;
    }
}
